package com.yunji.order.command.order.impl;

import com.yunji.common.event.SpringEventBus;
import com.yunji.common.event.entity.EventData;
import com.yunji.order.command.order.AbsOrderCommand;
import com.yunji.order.domain.OrderDO;
import com.yunji.order.domain.OrderDetailDO;
import com.yunji.order.dto.cmd.OrderCreateCommandDTO;
import com.yunji.order.event.OrderCouponEvent;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author : peter-zhu
 * @date : 2025/3/5 10:28
 * @description : TODO
 **/
@Log4j2
@Component
public class OrderCreateCommand extends AbsOrderCommand<OrderCreateCommandDTO, Long> {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long execute(OrderCreateCommandDTO cmd) {
        OrderDO order = cmd.getOrderDO();
        orderService.createOrder(order);
        List<OrderDetailDO> detailList = cmd.getDetailList();
        for (OrderDetailDO detail : detailList) {
            detail.setOrderId(order.getOrderId());
            detail.setOrderCode(order.getOrderCode());
            detail.setBelongId(order.getBelongId());
        }
        orderService.createOrderDetails(detailList);
        SpringEventBus.getInstance().publish(new EventData<>(new OrderCouponEvent(cmd.getCouponId(), order)));
        // 订单自动取消延迟队列
        redissonQueue.setCancelQueue(order);
        // 放入计时器
        return cmd.getOrderDO().getOrderId();
    }
}